#include "tfrmupdatplugin.h"
#include "ui_tfrmupdatplugin.h"
#include "tcommandexecprocess.h"
#include <QDebug>
#include <QHBoxLayout>
#include <QTimer>

TFrmUpDatPlugin::TFrmUpDatPlugin(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TFrmUpDatPlugin),m_teLog(nullptr),m_serverHandle(-1)
{
    ui->setupUi(this);

    m_teLog = new QTextEdit(this);
    QHBoxLayout *hblayout_center = new QHBoxLayout;
    hblayout_center->addWidget(m_teLog);
    setLayout(hblayout_center);

    m_teLog->setReadOnly(true);

    //定时发送保持连接消息
    QTimer *tmKeepConnect = new QTimer(this);
    connect(tmKeepConnect,&QTimer::timeout,this,&TFrmUpDatPlugin::slotSendKeepConnectMessage);
    tmKeepConnect->start(1000);
}

TFrmUpDatPlugin::~TFrmUpDatPlugin()
{
    delete ui;
}

void TFrmUpDatPlugin::showLog(const QString &logStr)
{
    m_teLog->append(logStr);
}

/**
 * @brief 设置服务器句柄
 * @param serverHandle 服务器句柄
 */
void TFrmUpDatPlugin::setServerHandle(int serverHandle)
{
    m_serverHandle = serverHandle;
    ::PostMessageW((HWND)m_serverHandle,LRWM_UPDATPLUGIN_KEEPCONNECT,NULL,(LPARAM)winId());
}

/**
 * @brief
 * @param eventType
 * @param message
 * @param result
 * @return
 */
bool TFrmUpDatPlugin::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);
    switch (msg->message) {
    case LRWM_UPDATPLUGIN_EXIT: {
        exit(0);
        break;
    }
    }

    return QWidget::nativeEvent(eventType,message,result);
}

/**
 * @brief 升级消息
 * @param message 消息
 * @param exitApp 是否需要退出
 */
void TFrmUpDatPlugin::slotUpdatMessage(int message,bool exitApp)
{
    ::PostMessageW((HWND)m_serverHandle,message,NULL,NULL);
    if(exitApp) {
        exit(0);
    }
}

/**
 * @brief 打印日志
 * @param logStr 日志
 */
void TFrmUpDatPlugin::slotShowLog(const QString &logStr)
{
    m_teLog->append(logStr);
}

/**
 * @brief 发送保持连接指令
 */
void TFrmUpDatPlugin::slotSendKeepConnectMessage()
{
    ::PostMessageW((HWND)m_serverHandle,LRWM_UPDATPLUGIN_KEEPCONNECT,NULL,(LPARAM)winId());
}
